package org.jvm.instruction.references.array.newarray;

import org.jvm.instruction.base.*;
import org.jvm.rtda.Object;
import org.jvm.rtda.heap.Klass;
import org.jvm.rtda.heap.classLoader.KlassLoaderRegister;
import org.jvm.rtda.heap.symref.ClassRef;
import org.jvm.rtda.thread.*;

/**
 * 创建引用类型数组
 * 字节码操作数指向类常量池中的类符号引用，类符号引用是数组的成员类
 *
 * @author 海燕
 * @date 2023/2/14
 */
public class ANEW_ARRAY extends Index16Instruction {

    @Override
    public void execute(Frame frame) {
        //解析数组的成员类型，根据成员类型的类名拼接数组类名
        ClassRef classRef = (ClassRef) frame.getMethod().getKlass().getConstantPool().getConstant(this.index);
        String arrayClassName = "[L" + classRef.resolvedClass(frame.getThread()).getName() + ";";
        OperandStack operandStack = frame.getOperandStack();
        //数组长度
        int count = operandStack.popInt();
        //数组里直接使用根类加载器进行加载
        Klass arrayClass = KlassLoaderRegister.getBootKlassLoader().loadKlass(arrayClassName);
        Object arrObject = InstructionUtil.newMultDimensionalArray(0, new int[]{count}, arrayClass);
        operandStack.pushRef(arrObject);
    }
}
